// 导入uni-id-common模块和数据库
// 使用相对路径引用uni_modules中的模块
const uniID = require('../../../../uni_modules/uni-id-common/uniCloud/cloudfunctions/common/uni-id-common/index.js');
const db = uniCloud.database();
const _ = db.command;
// 导入配置中心
const createConfigCenter = require('../../../uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/index.js');

/**
 * 回复评论
 * @param {Object} event 客户端传入的参数
 * @param {String} event.token 用户token
 * @param {String} event.postId 动态ID
 * @param {String} event.parentId 父评论ID
 * @param {String} event.content 回复内容
 * @param {Object} context 上下文信息
 */
exports.main = async (event, context) => {
  const { token, postId, parentId, content } = event;
  
  // 初始化配置中心并获取uni-id配置
  const config = createConfigCenter({ pluginId: 'uni-id' });
  const uniIdConfig = config.config();
  
  // 初始化uniID实例
  const uniIDIns = uniID.createInstance({
    context,
    config: uniIdConfig
  });
  
  // 校验参数
  if (!token) {
    return {
      code: 1,
      message: '请先登录'
    };
  }
  
  if (!postId || !parentId) {
    return {
      code: 1,
      message: '动态ID和父评论ID不能为空'
    };
  }
  
  if (!content || content.trim().length === 0) {
    return {
      code: 1,
      message: '回复内容不能为空'
    };
  }
  
  if (content.length > 200) {
    return {
      code: 1,
      message: '回复内容不能超过200个字符'
    };
  }
  
  try {
    // 校验token
    const checkTokenRes = await uniIDIns.checkToken(token);
    if (checkTokenRes.code) {
      return {
        code: checkTokenRes.code,
        message: checkTokenRes.errMsg || '登录状态失效，请重新登录'
      };
    }
    
    // 获取用户ID
    const userId = checkTokenRes.uid;
    
    // 检查动态是否存在
    const postRes = await db.collection('dynamic_posts').doc(postId).get();
    
    if (!postRes.data) {
      return {
        code: 1,
        message: '动态不存在'
      };
    }
    
    const post = postRes.data;
    
    // 检查父评论是否存在
    const commentsCollection = db.collection('comments');
    const parentCommentRes = await commentsCollection.doc(parentId).get();
    
    if (!parentCommentRes.data) {
      return {
        code: 1,
        message: '父评论不存在'
      };
    }
    
    const parentComment = parentCommentRes.data;
    
    // 检查权限
    if (post.privacy === 'private' && post.userId !== userId) {
      // 检查是否是关注者
      const followRes = await db.collection('user_follows')
        .where({
          userId: userId,
          followId: post.userId
        })
        .count();
      
      if (followRes.total === 0) {
        return {
          code: 1,
          message: '无权限回复此评论'
        };
      }
    } else if (post.privacy === 'followers' && post.userId !== userId) {
      // 检查是否是关注者
      const followRes = await db.collection('user_follows')
        .where({
          userId: userId,
          followId: post.userId
        })
        .count();
      
      if (followRes.total === 0) {
        return {
          code: 1,
          message: '无权限回复此评论'
        };
      }
    }
    
    // 查询当前用户信息
    const userRes = await db.collection('uni-id-users').doc(userId).get();
    if (!userRes.data) {
      return {
        code: 1,
        message: '用户不存在'
      };
    }
    
    // 查询被回复用户信息
    let replyToUserInfo = null;
    if (parentComment.userId !== userId) {
      const replyToUserRes = await db.collection('uni-id-users').doc(parentComment.userId).get();
      if (replyToUserRes.data) {
        replyToUserInfo = {
          userId: parentComment.userId,
          nickname: replyToUserRes.data.nickname || '用户' + parentComment.userId.substring(0, 6)
        };
      }
    }
    
    // 构建回复数据
    const replyData = {
      postId: postId,
      userId: userId,
      userInfo: {
        nickname: userRes.data.nickname || '用户' + userId.substring(0, 6),
        avatar: userRes.data.avatar || ''
      },
      content: content.trim(),
      parentId: parentId,
      replyTo: replyToUserInfo,
      createTime: new Date().getTime(),
      likeCount: 0
    };
    
    // 开始事务
    const transaction = await db.startTransaction();
    
    try {
      // 存储回复到数据库
      const newReplyResult = await transaction.collection('comments').add(replyData);
      
      // 查询插入后的回复数据
      const newReplyRes = await transaction.collection('comments').doc(newReplyResult.id).get();
      
      // 更新动态的评论数
      await transaction.collection('dynamic_posts')
        .doc(postId)
        .update({
          commentCount: _.inc(1)
        });
      
      // 提交事务
      await transaction.commit();
      
      // 查询更新后的评论数
      const updatedPostRes = await db.collection('dynamic_posts')
        .doc(postId)
        .field({ commentCount: true })
        .get();
      
      return {
        code: 0,
        message: '回复成功',
        data: {
          reply: newReplyRes.data,
          commentCount: updatedPostRes.data.commentCount
        }
      };
    } catch (error) {
      // 回滚事务
      await transaction.rollback();
      throw error;
    }
  } catch (error) {
    console.error('回复评论失败:', error);
    return {
      code: 1,
      message: '回复失败，请重试',
      data: error.message
    };
  }
};